﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace _模拟Post请求
{
    public static class DateTimeExtension
    {
        /// <summary>
        /// DateTime转Unix时间
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static long ToUnix(this DateTime time)
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            return (long)(DateTime.Now - startTime).TotalSeconds;
        }

        /// <summary>
        /// Unix 时间转Datetime
        /// </summary>
        /// <param name="unixTime"></param>
        /// <returns></returns>
        public static DateTime ToDateTimeByUnix(long unixTime)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(unixTime + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ToMd5Encryption(this string s)
        {
            StringBuilder sb = new StringBuilder();
            MD5 d5 = MD5.Create();
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(s);
            byte[] bytes = d5.ComputeHash(buffer);
            for (int i = 0; i < bytes.Length; i++)
            {
                sb.Append(bytes[i].ToString("x2"));
            }
            return sb.ToString();
        }
    }
}
